{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 环形链表的检测\n",
    "\n",
    "![Asked by Uber](https://img.shields.io/badge/Asked%20by-Uber-important?style=for-the-badge&logo=uber)\n",
    "\n",
    "&emsp;&emsp;给定一个链表，确定链表中是否有循环。为了便于表示，我们使用整数`pos`表示表尾连接到的回环下表位置：\n",
    "\n",
    "```text\n",
    "#   ┌─────┐\n",
    "#   ↓     ↑\n",
    "# 4 3 2 1 0\n",
    " In[1]: head = [4, 3, 2, 1, 0]\n",
    "        pos = 1\n",
    "\n",
    "Out[1]: True\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ListNode(object):\n",
    "    def __init__(self, x):\n",
    "        self.value = x\n",
    "        self.next = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "    def hasCycle(self, head):\n",
    "        if not head:\n",
    "            return False\n",
    "        slow = head\n",
    "        fast = head.next\n",
    "        while fast and fast.next and slow:\n",
    "            if fast == slow:\n",
    "                return True\n",
    "            fast = fast.next.next\n",
    "            slow = slow.next\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "head = ListNode(4)\n",
    "node_1 = ListNode(3)\n",
    "node_2 = ListNode(2)\n",
    "node_3 = ListNode(1)\n",
    "tail = ListNode(0)\n",
    "head.next = node_1\n",
    "node_1.next = node_2\n",
    "node_2.next = node_3\n",
    "node_3.next = tail\n",
    "tail.next = node_1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(Solution().hasCycle(head))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
